#update.py

import sys
import json
import requests
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QMessageBox
from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QDesktopServices


class UpdateChecker(QWidget):
    def __init__(self, local_version):
        super().__init__()
        self.local_version = local_version
        self.initUI()

    def initUI(self):
        self.setWindowTitle('软件更新检查')
        layout = QVBoxLayout()

        self.label = QLabel("正在检查更新...", self)
        layout.addWidget(self.label)

        self.check_button = QPushButton('检查更新', self)
        self.check_button.clicked.connect(self.check_for_updates)
        layout.addWidget(self.check_button)

        self.setLayout(layout)

    def check_for_updates(self):
        try:
            # 获取远程版本信息
            remote_version, download_url = self.get_remote_version_info()
            if remote_version is None or download_url is None:
                return

            # 比较版本
            if self.compare_versions(remote_version, self.local_version):
                self.show_update_dialog(download_url)
            else:
                self.label.setText("当前已是最新版本！")
        except Exception as e:
            print(f"Error checking for updates: {e}")
            self.label.setText("更新检查失败，请稍后再试。")

    def get_remote_version_info(self):
        url = "https://gitee.com/shareceo/soft_update/raw/master/test/updata_test"
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            return data["version"], data["url"]
        else:
            print(f"Failed to fetch version info, status code: {response.status_code}")
            return None, None

    @staticmethod
    def compare_versions(v1, v2):
        """简单比较版本号，v1 > v2 返回True"""
        v1_parts = list(map(int, v1.split('.')))
        v2_parts = list(map(int, v2.split('.')))

        for part1, part2 in zip(v1_parts, v2_parts):
            if part1 > part2:
                return True
            elif part1 < part2:
                return False
        return False

    def show_update_dialog(self, download_url):
        msg_box = QMessageBox()
        msg_box.setIcon(QMessageBox.Information)
        msg_box.setWindowTitle("发现新版本")
        msg_box.setText("发现新版本，是否立即下载？")
        msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg_box.buttonClicked.connect(lambda btn: self.on_download_clicked(btn, download_url))
        msg_box.exec_()

    def on_download_clicked(self, button, download_url):
        if button.text() == "&Yes":
            QDesktopServices.openUrl(QUrl(download_url))


if __name__ == '__main__':
    app = QApplication(sys.argv)

    # 假设本地版本为'1.0.0'
    local_version = '1.0.0'

    window = UpdateChecker(local_version)
    window.show()

    sys.exit(app.exec())